

import * as orderInsert from './mall-order-insert/Handler';
import * as orderQuery from './mall-order-query/Handler';
import * as orderUpdate from './mall-order-update/Handler';
import * as orderStatic from './mall-order-static/Handler';
import { AuthWrapper } from './auth/AuthWrapper';
import * as Utils from './utils/Utils.js';

let myHandler = async function (event, context, callback, logger) {
  const credential = Utils.getCredential(context, logger);
  let operation;
  let params;
  let token;

  operation = event.body ? JSON.parse(event.body).operation : event.operation;
  params = event.body ? JSON.parse(event.body).params : event.params;
  token = event.body ? JSON.parse(event.body).token : event.token;

  logger.info("the operation is " + event.operation);

  if (operation==="order_static"){
    try {
      orderStatic.myHandler(params, context, callback, logger);
    }catch(ex){
      callback({
        ret: { code: -1, desc: "orderStatic error" }
      });
    }

  }else {
    try {
      const authWrapper = new AuthWrapper(credential, logger);
      const promise = authWrapper.verifyToken(token);
      promise
        .then((res) => {
          switch (operation) {
            case "insert":
              orderInsert.myHandler(params, context, callback, logger);
              break;
            case "query":
              orderQuery.myHandler(params, context, callback, logger);
              break;
            case "update":
              orderUpdate.myHandler(params, context, callback, logger);
              break;
            default:
              callback({
                ret: { code: -1, desc: "no such function" },
              });
          }
        })
        .catch((e) => {
          callback({
            ret: { code: -1, desc: "token verify failed" + e.getCode() },
          });
        });
      // switch (operation) {
      //   case "insert":
      //     orderInsert.myHandler(params, context, callback, logger);
      //     break;
      //   case "query":
      //     orderQuery.myHandler(params, context, callback, logger);
      //     break;
      //   case "update":
      //     orderUpdate.myHandler(params, context, callback, logger);
      //     break;
      //   default:
      //     callback({
      //       ret: { code: -1, desc: "no such function" },
      //     });
      // }
    } catch (e) {
      logger.error("token is " + e);
      callback({
        ret: { code: -1, desc: "token verify failed" },
      });
    }
  }
};

module.exports.myHandler = myHandler;
